<?php

namespace Admin\Controller;
use Think\Controller;

class HoldController extends Controller{
	protected $type_content = array(
		'0' => '百家乐',
		'1' => '龙虎斗'
	);
	/**
	 * Created by PhpStorm.
	 * User: TheWay
	 * Date: 2019/3/13
	 * Time: 22:01
	 * 开盘按钮
	 * period_number  期号
	 * type           彩种 0百家乐 1龙虎斗
	 */
	public function start(){

		$post = $_REQUEST;
		$data = array();
		$period_number = $post['period_number'];
		$type = $post['type'];
		$prev_number = $period_number-1;
		//判断上期是否开奖
		$prev_info = M("hundred")->field("award_numbers")->where("period_number='$prev_number'  and type='$type'")->find();

		if(($prev_info['award_numbers'] == '' || $prev_info['award_numbers'] == '0')&&  $prev_info){
			$data['code'] = '401';
			$data['msg'] = '上期未开奖1';
			$data['content'] = '';
		}else {
			//首先判断期号
			if ($period_number == '' || $type == '') {
				$data['code'] = '400';
				$data['msg'] = '参数错误';
				$data['content'] = '';
			} else {
				$res = M("hundred")->field("id")->where("period_number='$period_number' and status='0' and type='$type'")->find();
				if ($res) {
					$edit_data = array(
						'status' => 1,
						'open_time' => time(),
					);
					M("hundred")->where("period_number='$period_number' and status='0' and type='$type'")->save($edit_data);
					$data['code'] = '200';
					$data['msg'] = '开盘成功';
					$data['content'] = '';
					$content = array(
						'time' => date('H:i:s'),
						"content" => $this->type_content[$type] . '第' . $period_number . '期已开盘'
					);
					$this->http_post2($content,'',$type);
                    $new_message = array(
                        'delay' => '0',
                        'type' => 'system',
                        'head_img_url' => '/Public/main/img/system.jpg',
                        'from_client_name' => '客服',
                        'content' => $content['content'] ,
                        'time' => date('H:i:s')
                    );
                    $this->add_message($new_message,$type);/*添加信息*/
				} else {
					$data['code'] = '400';
					$data['msg'] = '参数错误';
					$data['content'] = '';
				}
			}
		}
		echo json_encode($data);
	}

	/**
	 * Created by PhpStorm.
	 * User: TheWay
	 * Date: 2019/4/5
	 * Time: 0:06
	 * 核对倒计时10秒封盘提示
	 */
	public function tipStop(){
	    $type= $_REQUEST['type'];
		$content = array(
			'time' => date('H:i:s'),
			"content" => '距离封盘剩余10秒'
		);
        $new_message = array(
            'delay' => '0',
            'type' => 'system',
            'head_img_url' => '/Public/main/img/system.jpg',
            'from_client_name' => '客服',
            'content' => $content['content'] ,
            'time' => date('H:i:s')
        );
        $this->add_message($new_message,$type);/*添加信息*/
		$this->http_post2($content,'',$type);
	}

	/**
	 * Created by PhpStorm.
	 * User: TheWay
	 * Date: 2019/3/15
	 * Time: 12:25
	 * 封盘按钮
	 * period_number  期号
	 * type         彩种 0百家乐 1龙虎斗
	 */
	public function stop(){
		$post = $_REQUEST;
		$data = array();
		$period_number = $post['period_number'];
		$type = $post['type'];
		//首先判断期号
		if($period_number == '' || $type == ''){
			$data['code'] = '400';
			$data['msg']  = '参数错误';
			$data['content'] = '';
		}else{
			$res = M("hundred")->field("id")->where("period_number='$period_number' and status='1' and type='$type'")->find();
			if($res){
				$edit_data = array(
					'status'    => 0,
					'stop_time' => time(),
				);
				$edit = M("hundred")->where("period_number='$period_number' and status='1' and type='$type'")->save($edit_data);
				if($edit) {
					//添加下期数据
					$next_number = $period_number + 1;
					$next_info = M("hundred")->where("period_number='$next_number' and type='$type'")->find();
					if(!$next_info) {
						$next_data = array(
							'period_number' => $next_number,
							'type' => $type,
							'add_time' => time(),
						);
						M("hundred")->add($next_data);
					}
					$data['code'] = '200';
					$data['msg'] = '封盘成功';
					$data['content'] = $next_data;
					$content = array(
						'time' => date('H:i:s'),
						"content" => $this->type_content[$type].'第'.$period_number.'期已封盘'
					);
					$this->http_post2($content,'',$type);
                    $new_message = array(
                        'delay' => '0',
                        'type' => 'system',
                        'head_img_url' => '/Public/main/img/system.jpg',
                        'from_client_name' => '客服',
                        'content' => $content['content'],
                        'time' => date('H:i:s')
                    );
                    $this->add_message($new_message,$type);/*添加信息*/
				}else{
					$data['code'] = '401';
					$data['msg']  = '封盘失败';
					$data['content'] = '';
				}
			}else{
				$data['code'] = '400';
				$data['msg']  = '参数错误';
				$data['content'] = '';
			}
		}
		echo json_encode($data);
	}

    public function ccc()
    {
        $content = array(
            'time' => date('H:i:s'),
            "content" => '测试',
        );
        $this->http_post($content);
    }
    public function ccc2()
    {
        $content = array(
            'time' => date('H:i:s'),
            "content" => '测试2',
        );
        $this->http_post2($content,'',1);
    }
	/**
	 * Created by PhpStorm.
	 * User: TheWay
	 * Date: 2019/3/15
	 * Time: 12:42
	 * 录入结果
	 * period_number  期号
	 * type           彩种 0百家乐 1龙虎斗
	 * award_numbers  开奖结果 庄,庄对
	 * txt			  开奖庄闲牌记录 json
	 */
	public function enter(){
		$post = $_REQUEST;
		$data = array();
//		dump(dejiang($post['txt']));exit;
		$period_number = $post['period_number'];
		$type = $post['type'];
		if ($type==0){
            $award_int=implode(',',dejiang($post['txt']));
            $award_numbers = zhongjiang_fanyi(dejiang($post['txt']));
        }elseif($type==1){
            $award_int=dejiang_lh($post['txt']);
            $award_numbers = zhongjiang_lh_fanyi($award_int);
        }

		$txt = $post['txt'];
//		$award_numbers = implode(',',json_decode($award_numbers,true));
		//首先判断期号
		if($period_number == '' || $type == ''){
			$data['code'] = '401';
			$data['msg']  = '参数错误';
			$data['content'] = '';
		}else {
			$res = M("hundred")->field("id")->where("period_number='$period_number' and type='$type'")->find();
			if($res){
				$edit_data = array(
				    'award_int'=>$award_int,
					'award_numbers' => $award_numbers,
					'txt' 			=> $txt,
					'status'        => 2,
				);

				M("hundred")->where("period_number='$period_number' and type='$type'")->save($edit_data);
				$data['code'] = '200';
				$data['msg']  = '录入成功';
				$data['content'] = '';
				//判断是否需要推送
				$last_data = M("hundred")->limit(2)->order("id desc")->select();
				if($last_data[1]['period_number'] == $period_number){
					$content = array(
						'time'=>date('H:i:s'),
						"content" => $this->type_content[$type].'第'.$period_number.'期开奖结果为:'.$award_numbers,
					);
					$this->http_post2($content,'',$type);
                    $new_message = array(
                        'delay' => '0',
                        'type' => 'system',
                        'head_img_url' => '/Public/main/img/system.jpg',
                        'from_client_name' => '客服',
                        'content' => $content['content'] ,
                        'time' => date('H:i:s')
                    );
                    $this->add_message($new_message,$type);/*添加信息*/
				}
			}else{
				$data['code'] = '400';
				$data['msg']  = '参数错误';
				$data['content'] = '';
			}
		}
		echo json_encode($data);
	}

	/*
	 * 查询奖项
	 */
	function chaxun(){
        $post = $_REQUEST;
//        $data = array();
        if ($post['type']==0){
            $fy=zhongjiang_fanyi(dejiang($post['txt']));
        }elseif($post['type']==1){
            $fy=zhongjiang_lh_fanyi(dejiang_lh($post['txt']));
        }
        $a=['code'=>1,'data'=>$fy];
        echo json_encode($a);
    }

	/**
	 * Created by PhpStorm.
	 * User: TheWay
	 * Date: 2019/3/15
	 * Time: 16:03
	 * 历史记录列表
	 * type     彩种
	 */
	public function listHistory(){
		$post = $_REQUEST;
		$data = array();
		$type = $post['type'];
		$res = M('hundred')->field("id,period_number,type,award_numbers,status,stop_time")->where("type='$type' and is_ok=0")->order("id desc")->limit(20)->select();
		if($res){
			if($res[0]['award_numbers'] != '0'){
				$next_data = array(
					'period_number' => $res[0]['period_number']+1,
					'type' => $type,
					'add_time' => time(),
				);
				M("hundred")->add($next_data);
			}
			$data['content'] = $res;
		}else{
			$data['content'] = array();
		}
		$has_points = M("hundred_config")->field("has_points")->order("id desc")->find();
//		$this->http_post($content=array("has_points"=>$has_points['has_points']),0);
		$data['code'] = '200';
		$data['msg']  = '成功';
		echo json_encode($data);
	}

	/**
	 * Created by PhpStorm.
	 * User: TheWay
	 * Date: 2019/3/15
	 * Time: 16:04
	 * 历史记录类表详情
	 * period_number  期号
	 * type     	  彩种
	 */
	public function editHistory(){
		$post = $_REQUEST;
		$data = array();
		$type = $post['type'];
		$period_number = $post['period_number'];
		$res = M('hundred')->where("type='$type' and period_number='$period_number'")->find();
		if($res){
			$data['content'] = $res;
		}else{
			$data['content'] = (object)$res;
		}
		$data['code'] = '200';
		$data['msg']  = '成功';
		echo json_encode($data);
	}

	/**
	 * Created by PhpStorm.
	 * User: TheWay
	 * Date: 2019/3/23
	 * Time: 21:49
	 * 实时注单（显示当前开盘这一期的投注，列出庄、闲、和、庄对、闲对各项投注总额，另外计算出庒闲对冲后结果）
	 * type     	  彩种
	 */
	public function hundredNote(){
		$post = $_REQUEST;
		$data = array();
		$arr  = array();
		$type = $post['type'];

		$where=['type'=>$type];
		//查看当前开盘的这期期号
		$res = M('hundred')->field("period_number,open_time")->where($where)->limit(2)->order("id desc")->select();

        $period_number = $res[0]['period_number'];

		if ($res[0]['open_time']==0){
            $period_number=$res[1]['period_number'];
        }

		if($type == '0'){
			$game = 'hundred';
		}else{
			$game = 'longhu';
		}
		$zhuang    = 0;
		$xian      = 0;
        $he        = 0;
        $zhuangdui = 0;
        $xiandui   = 0;
        $duizhi=0;//对子
        $sanbao=0;//三宝
        $quzc_zhuang=0;//去占成的庄
        $quzc_xian=0;//去占成的闲
		$res_data = M("order")->where(['game'=>$game,'number'=>$period_number,'is_add'=>0])->select();
        foreach($res_data as $k=>$v){
            //用户竞猜号 约定为 json 如 {'庄':100,'庄对':100}
            if ('1'==$v['jincai_zl']){//庄'
                $quzc_zhuang+=$v['quzc_points'];
                $zhuang+=$v['del_points'];
            }
            if ('2'==$v['jincai_zl']){//闲'
                $quzc_xian+=$v['quzc_points'];
                $xian+=$v['del_points'];
            }
            if ('3'==$v['jincai_zl']){//和'
                $he+=$v['del_points'];
            }
            if ('4'==$v['jincai_zl']){//庄对'
                $zhuangdui+=$v['del_points'];
            }
            if ('5'==$v['jincai_zl']){//闲对'
                $xiandui=$v['del_points'];
            }
            if ('6'==$v['jincai_zl']){//对子'
                $duizhi+=$v['del_points'];
            }
            if ('7'==$v['jincai_zl']){//三宝'
                $sanbao+=$v['del_points'];
            }

        }

		if ($type == '0'){
            //对冲
            if ($zhuang>$xian){
                $dc='庄'.($zhuang-$xian);
            }elseif($zhuang<$xian){
                $dc='闲'.($xian-$zhuang);
            }else{
                $dc='-';
            }
            //去占成庄闲对冲
            if ($quzc_zhuang>$quzc_xian){
                $quzc_zx='庄';
                $quzc_dc=$quzc_zhuang-$quzc_xian;
            }elseif($quzc_zhuang<$quzc_xian){
                $quzc_zx='闲';
                $quzc_dc=$quzc_xian-$quzc_zhuang;
            }else{
                $quzc_dc=0;
            }
        }
		elseif($type == '1'){
            //对冲
            if ($zhuang>$xian){
                $dc='龙'.($zhuang-$xian);
            }elseif($zhuang<$xian){
                $dc='虎'.($xian-$zhuang);
            }else{
                $dc='-';
            }
            //去占成庄闲对冲
            if ($quzc_zhuang>$quzc_xian){
                $quzc_zx='龙';
                $quzc_dc=$quzc_zhuang-$quzc_xian;
            }elseif($quzc_zhuang<$quzc_xian){
                $quzc_zx='虎';
                $quzc_dc=$quzc_xian-$quzc_zhuang;
            }else{
                $quzc_dc=0;
            }
        }
        $vv='-';
        if ($quzc_dc>0){//计算吃码后的值 （吃码量的倍数  多的不计）
            if ($quzc_dc>=C('chima')){
                $vv=$quzc_dc-($quzc_dc%C('chima'));
                $vv=$quzc_zx.$vv;
            }
        }

		$arr['zhuang'] = $zhuang;
		$arr['xian'] = $xian;
        $arr['he'] = $he;
        $arr['dc']=$dc;//对冲（虚）
        $arr['dc_s']=$vv;//对冲（实 去占成算吃码）
        $arr['zhuangdui'] = $zhuangdui;
        $arr['xiandui'] = $xiandui;
        $arr['duizhi'] = $duizhi;//对子
        $arr['sanbao'] = $sanbao;//三宝
		$arr['zhuangxian'] = $zhuang-$xian;
		$data['code'] = '200';
		$data['msg']  = '成功';
		$data['content'] = $arr;
		echo json_encode($data);
	}

	/**
	 * Created by PhpStorm.
	 * User: TheWay
	 * Date: 2019/4/16
	 * Time: 23:05
	 * 一键撤注
	 * type     	  彩种
	 */
	public function clearBet(){
		$post = $_REQUEST;
		$data = array();
		$type = $post['type'];
		//获取当前期数
		$res = M('hundred')->field("period_number")->where("type='$type' and open_time!='0'")->order("id desc")->select();
		$period_number = $res[0]['period_number'];

		//获取当前期数所有投
		if($type == '0'){
			$types = 'hundred';
		}else{
			$types = 'longhu';
		}
		$list = M('order')->where("number = '$period_number' and state = 1 and is_add = 0 and game='$types'")->order("time ASC")->select();
//		dump($list);die;
		foreach($list as $k=>$v){
			M()->startTrans();
			try {
				$user_id = $v['userid'];
				$order_id = $v['id'];
				M('user')->where("id = $user_id")->setInc('points',$v['del_points']);
				M('order')->where("id = $order_id")->delete();
				M()->commit();
			} catch (Exception $e) {
				M()->rollback();
			}
			$content = array(
				'clear' => '1',
				'content' => $v['del_points'],
			);
            $this->http_post2($content,$user_id,$type);

        }
		$new_message = array(
			'type' => 'system',
			'head_img_url'=>'/Public/main/img/system.jpg',
			'from_client_name' => '客服',
			'content'=>"由于赌场牌手发牌失误，导致本局无效，谢谢谅解！",
			'time'=>date('H:i:s')
		);
        $this->http_post2($new_message,'',$type);

        $new_message2 = array(
            'delay' => '0',
            'type' => 'system',
            'head_img_url' => '/Public/main/img/system.jpg',
            'from_client_name' => '客服',
            'content' => $new_message['content'] ,
            'time' => date('H:i:s')
        );
        $this->add_message($new_message2,$type);/*添加信息*/
		$data['code'] = '200';
		$data['msg']  = '成功';
		$data['content']  = '';
		echo json_encode($data);
	}

	/**
	 * Created by PhpStorm.
	 * User: TheWay
	 * Date: 2019/4/20
	 * Time: 18:39
	 * type  彩种
	 */
	public function clearHistory(){
		$post = $_REQUEST;
		$data = array();
		$type = $post['type'];
		//查询所有未被删除的记录
		$res = M('hundred')->field('id')->where("type='$type' and is_ok=0 and award_numbers!='0'")->select();
		foreach($res as $k=>$v){
			$id = $v['id'];
			$edit = array('is_ok'=>1);
			M('hundred')->where("id='$id'")->save($edit);
		}
		$new_message = array(
			'type' => 'system',
			'head_img_url'=>'/Public/main/img/system.jpg',
			'from_client_name' => '客服',
			'content'=>"本局以结束，敬请期待下局开始！",
			'time'=>date('H:i:s')
		);
		$this->http_post2($new_message,'',$type);
        $new_message2 = array(
            'delay' => '0',
            'type' => 'system',
            'head_img_url' => '/Public/main/img/system.jpg',
            'from_client_name' => '客服',
            'content' => $new_message['content'] ,
            'time' => date('H:i:s')
        );
        $this->add_message($new_message2,$type);/*添加信息*/
		$data['code'] = '200';
		$data['msg']  = '成功';
		$data['content']  = '';
		echo json_encode($data);

	}

	/**
	 * Created by PhpStorm.
	 * User: TheWay
	 * Date: 2019/5/18
	 * Time: 15:17
	 * 设置筹码
	 * bet_points 筹码点数
	 */
	public function publishPoints(){
		$post = $_REQUEST;
		$data = array();
		$add_data = array();
		$add_data['bet_points'] = $post['bet_points'];
		$add_data['has_points'] = $post['bet_points'];
        $add_data['type'] = $post['type'];
        $add_data['add_time'] = time();
		$res = M("hundred_config")->add($add_data);
		if($res) {
			$data['code'] = '200';
			$data['msg'] = '成功';
		}else{
			$data['code'] = '400';
			$data['msg'] = '失败';
		}
		$data['content']  = '';
		echo json_encode($data);
	}

	/**
	 * Created by PhpStorm.
	 * User: TheWay
	 * Date: 2019/5/24
	 * Time: 10:57
	 * 查询实时码量
	 */
	public function findBet(){
		$post = $_REQUEST;
		$data = array();
		$where['type']=$post['type'];
		$res = M("hundred_config")->where($where)->order("id desc")->find();
		$data['code'] = '200';
		$data['msg'] = '成功';
		$data['content']  = $res;
		echo json_encode($data);
	}

	/**
	 * Created by PhpStorm.
	 * User: TheWay
	 * Date: 2019/3/16
	 * Time: 0:03
	 * curl 推送数据
	 * type 彩种
	 * post_data 推送数据
	 */
	public function http_post($content,$to_uid = ""){
		// 指明给谁推送，为空表示向所有在线用户推送
		// 推送的url地址，上线时改成自己的服务器地址
		$push_api_url = "http://localhost:12224/";//原12224会向所有用户推送
		$post_data = array(
			"type" => "publish",
			"content" => json_encode($content),
			"to" => $to_uid,
		);
		$ch = curl_init ();
		curl_setopt ( $ch, CURLOPT_URL, $push_api_url);
		curl_setopt ( $ch, CURLOPT_POST, 1 );
		curl_setopt ( $ch, CURLOPT_HEADER, 0 );
		curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
		curl_setopt ( $ch, CURLOPT_POSTFIELDS, $post_data );
		curl_setopt ($ch, CURLOPT_HTTPHEADER, array("Expect:"));
		$return = curl_exec ( $ch );
		curl_close ( $ch );
		return $return;
	}
//$fangjian  房间【0=》百家乐，1=》龙虎斗】
    public function http_post2($content,$to_uid = "",$fangjian=0){
        // 指明给谁推送，为空表示向所有在线用户推送
        // 推送的url地址，上线时改成自己的服务器地址
        $push_api_url = "http://localhost:12226/";//原12224会向所有用户推送
        $post_data = array(
            "type" => "publish",
            "content" => json_encode($content),
            "to" => $to_uid,
            'fangjian'=>$fangjian,
        );
        $ch = curl_init ();
        curl_setopt ( $ch, CURLOPT_URL, $push_api_url);
        curl_setopt ( $ch, CURLOPT_POST, 1 );
        curl_setopt ( $ch, CURLOPT_HEADER, 0 );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $post_data );
        curl_setopt ($ch, CURLOPT_HTTPHEADER, array("Expect:"));
        $return = curl_exec ( $ch );
        curl_close ( $ch );
        return $return;
    }
    protected function add_message($new_message,$type=0){
        if (!empty($new_message)) {
            if (0==$type)   {$new_message['game'] = 'hundred';}
            elseif(1==$type){$new_message['game'] = 'longhu';}
            $res = M('message')->add($new_message);
            return $res;
        }

    }
}

?>